package com.spring.crm.conf;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import javafx.application.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;

@Component
public class TokenUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(Application.class);

    /**
     * 过期时间500分钟
     */
    private static final long EXPIRE_TIME = 60 * 60 * 1000;
    private static final String secret = "CxqGrrIsXA82CF1b";

    /**
     * 生成token
     * @param userId    用户id
     * @return
     */
    public static String createToken(String userId){

            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            String token="";
            token= JWT.create().withAudience(userId) // 将 user id 保存到 token 里面
                    .withExpiresAt(date) //五00分钟后token过期
                    .sign(Algorithm.HMAC256(userId+secret)); // 以 password 作为 token 的密钥
            return token;
    }

//    public static TokenUtil tokenUtil;
//    @PostConstruct
//    public void init() {
//        tokenUtil = this;
//        tokenUtil.userMapper = this.userMapper;
//        tokenUtil.appTokenMapper = this.appTokenMapper;
//    }

    /**
     * 验证token是否有效
     * @param token  请求头中携带的token
     * @return  token验证结果  2-token过期；1-token认证通过；0-token认证失败
     */
    public static int verify(String token){
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            LOGGER.info("token get userId failed!");
            return 0;
        }
        LOGGER.info("token-verify*");
        LOGGER.info("username:"+userId);
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(userId+secret)).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            LOGGER.info("jwtVerifier.verify exception");
            return 0;
        }

        return 1;
    }
}
